package com.tubruk.trackme;

import com.tubruk.adapter.KMLAdapter;
import com.tubruk.database.TrackSummaryDB;
import com.tubruk.object.Global;
import com.tubruk.object.TrackSummary;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class Summary extends Activity {
	
	public static String OBJECT_SELECTED = "OBJECT_SELECTED";
	public static String ACTION_SELECTED = "ACTION_SELECTED";
	
	private static final int EXPORT_KML = 1;
	
	private TrackSummary sum;
	
	//menu+returned type
	public static final int MENU_SAVE = Menu.FIRST;
	private static final int MENU_MAP = Menu.FIRST + 1;
    private static final int MENU_EXPORT = Menu.FIRST + 2;
    public static final int MENU_DELETE = Menu.FIRST + 3;
    
	
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.summary);
	
	        sum = null;
	        Bundle extras = getIntent().getExtras();
	        if (extras != null){
	        	Object obj = extras.get(Summary.OBJECT_SELECTED);
	        	if (obj!= null) {
	        		sum = (TrackSummary) obj;
	        		
	        		TextView tv;
	            	
	            	tv = (TextView) this.findViewById(R.id.title);
	            	tv.setText(sum.getTitle());
	            	
	            	tv = (TextView) this.findViewById(R.id.starttime);
	            	tv.setText(sum.getTimeStartStr());
	            	
	            	tv = (TextView) this.findViewById(R.id.duration);
	            	tv.setText(sum.getTimeSpentStr());
	            	
	            	tv = (TextView) this.findViewById(R.id.distance);
	            	tv.setText(sum.getDistanceStr());
	            	
	            	tv = (TextView) this.findViewById(R.id.min);
	            	tv.setText(sum.getMinSpeedStr());
	            	
	            	tv = (TextView) this.findViewById(R.id.avg);
	            	tv.setText(sum.getMinSpeedStr());
	            	
	            	tv = (TextView) this.findViewById(R.id.max);
	            	tv.setText(sum.getMaxSpeedStr());
	            
	        	}
	        	
	        }
	        
	        ImageButton locate = (ImageButton) findViewById(R.id.locate);
			locate.setOnClickListener(new LocateClickListener());

			Button export = (Button) findViewById(R.id.export);
			export.setOnClickListener(new FileManager());
	 }
	 
	 @Override
	 public boolean onOptionsItemSelected(MenuItem menu){
		 Intent i;
		 
		 switch(menu.getItemId()) {
		 case MENU_SAVE:
			 i = new Intent();
			 TextView tv = (TextView) this.findViewById(R.id.title);
         	 sum.setTitle(tv.getText().toString());
			 
         	 i.putExtra(Summary.OBJECT_SELECTED, sum);
         	 i.putExtra(Summary.ACTION_SELECTED, MENU_SAVE);
         	 setResult(Activity.RESULT_OK, i);
         	 
         	 finish();		 
			 break;
		 case MENU_EXPORT:
			 i = new Intent (Summary.this, FileBrowser.class);
			 i.putExtra(FileBrowser.MODE_TYPE, FileBrowser.MODE_BROWSE_ADDNEWFILE);
			 startActivityForResult(i, Summary.EXPORT_KML);
			 break;
		 case MENU_DELETE:
			 AlertDialog.Builder builder = new AlertDialog.Builder(this);
			 builder.setMessage("Are you sure you want to delete?")
			        .setCancelable(false)
			        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int id) {
			            	Intent i = new Intent();
			   			 
			            	 i.putExtra(Summary.OBJECT_SELECTED, sum);
			            	 i.putExtra(Summary.ACTION_SELECTED, MENU_DELETE);
			            	 setResult(Activity.RESULT_OK, i);
			            	 
			                 finish();
			            }
			        })
			        .setNegativeButton("No", new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int id) {
			                 dialog.cancel();
			            }
			        });
			 AlertDialog alert = builder.create();
			 alert.show();
			 
			 break;
		 }
		 
		 return super.onOptionsItemSelected(menu);
	 }
	 
	 public boolean onCreateOptionsMenu(Menu menu) {
	        super.onCreateOptionsMenu(menu);
	        
	        menu.add(0, MENU_SAVE, 0, "Save")
			.setIcon(android.R.drawable.ic_menu_save);
	        
	        menu.add(0, MENU_MAP, 0, "Map")
			.setIcon(android.R.drawable.ic_menu_mylocation);
			
	        menu.add(0, MENU_EXPORT, 0, "Export KML")
				.setIcon(android.R.drawable.ic_menu_rotate);
			
	        menu.add(0, MENU_DELETE, 0, "Delete")
				.setIcon(android.R.drawable.ic_menu_delete);
	     
	        return true;
			
	    }
	 
	 private class LocateClickListener implements OnClickListener {

			public void onClick(View v) {
				finish();
				Intent i = new Intent( Summary.this, TrackMapActivity.class);
				startActivity(i);
			}
			
		}

	 private class FileManager implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent i = new Intent (Summary.this, FileBrowser.class);
			i.putExtra(FileBrowser.MODE_TYPE, FileBrowser.MODE_BROWSE_ADDNEWFILE);
			startActivityForResult(i, Summary.EXPORT_KML);
		}
		 
	 }
	 
	 @Override 
		public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		  super.onActivityResult(requestCode, resultCode, data); 
		  switch(requestCode) { 
		    case (Summary.EXPORT_KML) : { 
		      if (resultCode == Activity.RESULT_OK) { 
		    	 
		    	 String path = data.getStringExtra(FileBrowser.RESULT_PATH);
		    	 boolean addExtension = true;
		    	 if (path != null) {
		    		 String[] args = path.split("\\.");
		    		 if (args.length > 1) {
		    			 String extension = args[args.length - 1];
		    			 if (extension.toLowerCase().equals("kml")){
		    				 addExtension = false;
		    			 }
		    		 }
		    	 }
		    	 
		    	 if (addExtension){
		    		 path = path + ".kml";
		    	 }
		    	 
		    	 TrackSummaryDB.getTrackSummaryDetails(sum);
		    	 int result = KMLAdapter.generateKML(path, sum);
		    	 
		    	 CharSequence text = "";
		    	 if (result == KMLAdapter.KML_GENERATE_SUCCESS) {
			    	 text = "Data has been exported to:\n" + path;
		    	 }else {
		    		 text = "Unable to write file:\n" + path + "\nPlease choose different directory or external storage";
		    	 }
		    	 
		    	 Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
		    	 toast.show();
		      } 
		      break; 
		    } 
		  } 
		}
}
